package com.kun.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kun.context.LoginMemberContext;
import com.kun.resp.MemberLoginResp;
import com.kun.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @className: MemberInterceptor
 * @Description: 拦截器，拦截请求，获取其中的token，并转化为member
 * @author: kunkun
 * @date: 2025/7/26 17:56
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    private Logger LOG = LoggerFactory.getLogger(MemberInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取header的token参数
        String token = request.getHeader("token");
        if (StrUtil.isNotBlank(token)){
            LOG.info("获取会员的token信息：{}",token);
            JSONObject loginMember = JwtUtil.getJSONObject(token);
            MemberLoginResp member = JSONUtil.toBean(loginMember, MemberLoginResp.class);
            //1.1 存储到ThreadLocal中
            LoginMemberContext.setMember(member);
        }
        //2. 放行
        return true;
    }
}
